package cars;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class mmm {

	/**统计不同品牌的车在每个月的销售量分布
	 * @param args
	 */
	public static void main(String[] args)throws Exception {
		if (args.length!=2) {
			System.err.println("user path err!");
			System.exit(-1);
		}
		@SuppressWarnings("deprecation")
		Job job=new Job(new Configuration(),"citycars");
		job.setJarByClass(mmm.class);
		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));
		
		job.setMapperClass(cMap.class);
		job.setReducerClass(cReducer.class);
		
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(IntWritable.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		
		job.waitForCompletion(true);
		
	}
	public  static class cMap extends Mapper<LongWritable, Text,Text,IntWritable>{
		protected void map(LongWritable key, Text value, org.apache.hadoop.mapreduce.Mapper<LongWritable,Text,Text,IntWritable>.Context context) throws java.io.IOException ,InterruptedException {
			String[] lines = value.toString().split("\t");
			if (lines.length>8 &&lines[7]!="" && lines[3]!="" && lines[2]!="" && lines[7]!=null && lines[3]!=null && lines[2]!=null ) {
				String city=lines[2].trim();//shi
				String county=lines[3].trim();//xian,qu
				String brand=lines[7].trim();
				context.write(new Text(city+"-"+county+"-"+brand), new IntWritable(1));
				
				//map的中间结果是《长治市-长治城区，1》
			}
		};
	}
	//shuffle处理后的结果：《长治-城区，『1，1，1，1』》
	public static class cReducer extends Reducer<Text, IntWritable,Text,IntWritable>{
		protected void reduce(Text k2, java.lang.Iterable<IntWritable> values, org.apache.hadoop.mapreduce.Reducer<Text,IntWritable,Text,IntWritable>.Context context) throws java.io.IOException ,InterruptedException {
			int sum=0;
			for (IntWritable count : values) {
				sum+=count.get();
				
			}
			context.write(k2, new IntWritable(sum));
		};
	}
		
}

